package com.example.myapplicationwork;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private RecyclerView recyclerView;
    private ItemAdapter adapter;
    private ItemViewModel viewModel;
    private SwipeRefreshLayout swipeRefreshLayout;
    private List<ItemModel> itemList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = view.findViewById(R.id.recyclerView);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);

        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ItemAdapter(itemList, this::onItemClick, this::onItemLongClick);
        recyclerView.setAdapter(adapter);

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(ItemViewModel.class);

        // 观察数据变化
        viewModel.getItemsLiveData().observe(getViewLifecycleOwner(), items -> {
            itemList.clear();
            itemList.addAll(items);
            adapter.updateData(itemList);
            swipeRefreshLayout.setRefreshing(false);
        });

        // 设置下拉刷新
        swipeRefreshLayout.setOnRefreshListener(() -> {
            // 触发数据重新加载
            viewModel.loadItems();
        });

        return view;
    }

    // 处理列表项点击事件
    private void onItemClick(ItemModel item) {
        // 跳转到详情页，并传递数据
        Intent intent = new Intent(getActivity(), DetailActivity.class);
        intent.putExtra("item", item);
        startActivity(intent);
    }

    // 处理列表项长按事件
    private void onItemLongClick(ItemModel item) {
        // 显示确认对话框
        new AlertDialog.Builder(requireContext())
                .setTitle("删除确认")
                .setMessage("确定要删除 \"" + item.getTitle() + "\" 吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    // 删除项目
                    viewModel.deleteItem(item.getId());
                    Toast.makeText(getContext(), "已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }
}